Skip to content

Add reasoning streaming events and support Gemma 4 channels - #563

Merged
davidkoski merged 13 commits into
ml-explore:mainfrom
abra-code:reasoning-generation-events
Oct 28, 2026
Merged

davidkoski merged 13 commits into
ml-explore:mainfrom
abra-code:reasoning-generation-events

Conversation

@abra-code

Copy link
Copy Markdown
Contributor

Proposed changes

Part 1: Support Gemma 4's labeled reasoning channels
ReasoningConfig describes a reasoning protocol as a delimiter pair, which Gemma 4 does not use. Its delimiters are special tokens (soc_token id 100 <|channel>, eoc_token id 101 <channel|>) and the opening token is followed by a role label, terminated by a newline, that names the span:

<|channel>thought\n ... <channel|>the answer

A pair cannot carry that. Anchored on "<|channel>" it emits the label as the first word of the thinking; anchored on "<|channel>thought\n" it stops matching the moment the label is anything else and leaks the raw opener into the answer.

Add ReasoningChannel, carried as an optional ReasoningConfig.channel, and give ReasoningEventEmitter a label state. nil keeps the pair protocol exactly as it was, so Qwen3 and DeepSeek-R1 are unchanged and the existing ReasoningEventEmitterTests are untouched.

The label is consumed as metadata rather than emitted; a label not listed as a response label routes to reasoning, so an unknown channel stays readable and cannot leak markers into the answer; hold-back covers the longest watched delimiter, since both Gemma 4 tokens are 10 characters and a splitter sized for tears them; an opener whose label never terminates settles into a visible body instead of buffering without bound; and a stray end delimiter with no opener is swallowed, because a special token arriving alone means the prompt opened the channel and it cannot be prose the model typed.

ReasoningChannel.gemma4 lists "content" as a response label defensively rather than from observation: no shipped Gemma 4 template emits such a channel, and Google's own x-regex response schema names the answer group "content" while leaving it outside any channel. Listing it costs nothing and means a channel-wrapped answer would not be hidden in the thought stream if one ever did appear.

The four Gemma 4 model types declare the protocol themselves through ChatConventionsProviding, as NanbeigeModel already does.

Also add a token-id overload of promptEndsInsideReasoning so the prompt-tail rule has one implementation rather than two.

Part 2: Add reasoning on the streaming API as Generation.reasoning
Nothing on the standard generation path reads ModelConfiguration.reasoningConfig.
StandardTokenStreamDecoder wraps ToolCallProcessor, which only knows tool syntax.
Raw ... therefore reached Generation.chunk with its delimiters
still attached. ChatSession then copied it into the recorded assistant message,
so thinking text was replayed into every later prompt. These families' own chat
templates strip it out. Gemma 4's <|channel>thought markers are the visible form
of the same gap.

Give StandardTokenStreamDecoder an optional ReasoningEventEmitter. It splits
reasoning out after the stop-string filter and before the tool-call parser.
Order matters in both directions. Splitting first means a model that writes
<|tool_call> in its scratchpad cannot produce a phantom tool call. finish()
drains the scanner before the processor's EOS, so an end delimiter that never
arrives as text cannot strand held-back thinking. A model with no
ReasoningConfig decodes nothing and costs nothing.

Framed token protocols decode their own reasoning. makeTokenStreamDecoder
returns the protocol decoder before it builds the standard one, so the reasoning
argument is dropped there. Muse-Glimmer declares both .atem and a
ReasoningConfig, and gets only the Onyx decoder.

Add Generation.reasoning(String) and emit it instead of dropping it. Routing
reasoning out without exposing it would delete text callers get today. The
existing drop arrived with the Onyx protocol in PR #523, "Add Muse-Glimmer, a
30B agentic multimodal model, with ATEM tool calling". It covered only framed
protocols, which had no public reasoning to lose. Adding a case to a public
non-frozen enum breaks exhaustive switches downstream. Every in-repo site is
updated, including those the package scheme never builds.

DeepSeek-R1 prefills into the prompt and generates only the closing tag.
A scanner that starts outside would send the thought to the answer, then send
the answer to reasoning. Every generate() overload computes priming from the
prompt it already holds. generateTask takes it as a defaulted parameter, for
callers that drive the loop themselves. Only the prompt tail is read.

ChatSession counts a thinking-only turn as a turn that happened. Reasoning never
enters the assistant message. It is dropped from replayed history, the way these
families' templates do it. A model that runs out of maxTokens inside its thought
block therefore leaves content empty. If that looked like an empty generation,
the rollback would remove the user's message from the transcript too.

MLXFoundationModels drops .reasoning on its unconstrained path. Anything with a
resolved config goes to runReasoning instead. Reaching that path means the
caller did not ask for .reasoning and the prompt was rendered with thinking off.
Surfacing it would be the leak the capability gate exists to stop.

Co-Authored-By: Claude

Checklist

Put an x in the boxes that apply.

  • I have read the CONTRIBUTING document
  • I have run pre-commit run --all-files to format my code / installed pre-commit prior to committing changes
  • I have added tests that prove my fix is effective or that my feature works
  • I have updated the necessary documentation (if needed)

@abra-code

Copy link
Copy Markdown
Contributor Author

This PR supersedes the the Part 1-only PR: #504

@davidkoski

Copy link
Copy Markdown
Member

rebased to main, mostly to pick up #548 which had some changes in the same area

@davidkoski

Copy link
Copy Markdown
Member

Rebase to main


// Finished reasoning that was streamed apart from `content`, kept for
// templates that replay it.
package var reasoning: String? = nil

@davidkoski davidkoski Oct 23, 2026 •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is hooked up in Qwen3VLMessageGenerator, but I don't see it anywhere else.

For other models that support reasoning, maybe add this in the default implementation:

extension MessageGenerator {

    public func generate(message: Chat.Message) -> Message {
...
        if let reasoning = message.reasoning {
            dictionary["reasoning_content"] = reasoning
        }

models / templates that want it will pick it up, those that don't won't.

Does it need to be added to other MessageGenerator implementations? GPTOSS, Gemma4, etc?

I will attach repro tests to illustrate. See qwen3LLMGeneratorDropsReasoning and qwen3LLMToolLoopRewindsCache.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed, that was a behavior change. The default MessageGenerator.generate(message:) and Gemma4MessageGenerator now pass message.reasoning as reasoning_content. Your tool-loop repros are in ReasoningReplayTests and keep the cache. They also showed a whitespace issue: a newline before the close could stream as reasoning so Gemma's re-render doubled it. A thought's trailing whitespace is now held until the close so the recorded thought does not depend on token boundaries.
See the fixes here: c93d8f8

Comment thread Libraries/MLXLMCommon/Evaluate.swift Outdated
tools: tools,
toolCallPolicy: parameters.toolCallPolicy)
toolCallPolicy: parameters.toolCallPolicy,
reasoningPrimedInside: promptPrimesReasoning(

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The call to TokenIterator (above) queues the prefill on the GPU. This call to promptPrimesReasoning slices the input (tokens[(tokens.size - count)...].asArray(Int.self)) which will run after the prefill is done. On a long prompt that might be a while.

Thoughts (in order of preference):

  • run the promptPrimesReasoning() before the TokenIterator is constructed
  • the tokens is probably already evaluated, maybe it can be read as an array and sliced on the swift side
  • a secondary stream could be used to make it interleave with the prefill

One of the other overloads (deprecated) builds the token iterator outside -- i think that can be left alone.

See repro test generateReadsPromptTailAfterPrefill

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Per your suggestion, moved the read before the iterator is built in the plain, speculative and MTP 'generate' functions.
The deprecated overload that takes an iterator is not changed.
Each has a test that the prompt is decoded before the first forward pass
See the change: cebc965

Comment thread Libraries/MLXLMCommon/ChatSession.swift Outdated
toolCallPolicy: generateParameters.toolCallPolicy,
// The whole prompt, not `input`: the cache may leave
// less than the prefill to prefill.
reasoningPrimedInside: promptPrimesReasoning(

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is doing similar work to ChatSession.prefilledReasoningStartDelimiter() / ReasoningEventEmitter.promptEndsInsideReasoning in decoding the tail.

Same code is below on 1496.

This could do the tail decode once, e.g. around where prefilledReasoningStartDelimiter is declared, something like:

let preparedInput = try await processor.prepare(input: userInput)
let promptTokenIds = preparedInput.text.tokens.asArray(Int.self)
let reasoningPrimedInside = modelConfiguration.reasoningConfig.map {
   ReasoningEventEmitter.promptEndsInsideReasoning(
       promptTokens: promptTokenIds, config: $0, tokenizer: tokenizer)
} ?? false
let prefilledReasoningStartDelimiter =
   reasoningPrimedInside ? modelConfiguration.reasoningConfig?.startDelimiter : nil             

If Evaluate is fixed this shouldn't stall, but it does extra work.

See chatSessionDecodesPromptTailTwice in repro tests.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done: the session decides priming once per turn, before the prefill, and derives 'prefilledReasoningStartDelimiter' from it.
See: cebc965

/// suppresses the generation prompt entirely after a tool call or tool response.
/// The model then opens the channel itself, so without this config its delimiters
/// reach the caller as literal text.
public static let gemma4 = ReasoningConfig(

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Consider:

<|channel>thought
I need the weather
<|tool_call>call:get_weather{city:<|"|>Paris<|"|>}<tool_call|>

Should the <|tool_call> also be a delimiter? Models are sometimes sloppy about closing tags. See gemma4ToolCallInsideUnclosedChannelIsLost in repro tests.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Changed. <|tool_call> is now an implicit end for Gemma 4, as <tool_call> is for Qwen.
See: 69071be

@davidkoski davidkoski left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added a couple questions/comments. Here are some repro tests I had claude generate to illustrate.

I think the split of thinking out of the main stream and lack of hookup on the MessageGenerators is probably the biggest issue (change in behavior for models outside of this PR).

The blocking during prefill with promptPrimesReasoning() is not a correctness issue but probably worth fixing -- it will be one of those surprises down the line.

The ChatSession duplicate decodes are also not a correctness issue.

Finally, I am not sure if the tool call inside the thinking should generate a tool call, but we do have this kind of recovery for other tool call situations, so it is probably reasonable.

See what you think. Thank you!

ReproTests.swift.zip

@abra-code

Copy link
Copy Markdown
Contributor Author

Thanks for the review. I will look into the reported issues.

…n-events

Resolve conflicts with ml-explore#714: the reasoning setup moves into ChatSession's startGeneration, and the exhaustive Generation switch test gains .reasoning.

# Conflicts:
#	Libraries/MLXLMCommon/ChatSession.swift
#	Libraries/MLXLMCommon/Evaluate.swift
ChatSession records a finished thought beside the assistant message. Only the Qwen3-VL generator passed it back to the chat template, so for other models a tool loop re-rendered history without the thought and the prompt cache rewound.

The default and Gemma 4 message generators now pass it as reasoning_content, which the Qwen3 and Gemma 4 templates read. GPT-OSS and Onyx still do not replay their reasoning channels as before.

Hold a thought's trailing whitespace until it is known whether the thought closes, so the recorded thought does not depend on how tokens split it and matches what the template re-renders.
promptPrimesReasoning reads the prompt tail out of an MLXArray. Building the token iterator queues the prefill so reading the tail afterwards waited for the whole prefill on long prompts.

The plain, speculative and MTP generate functions now decide priming before they build the iterator. ChatSession decides it once per turn before the prefill and derives prefilledReasoningStartDelimiter from it instead of decoding the prompt tail twice.
A Gemma 4 model can open a tool call without closing its thought channel first. The call was then swallowed as reasoning and never reached the tool-call parser.

The gemma4 preset now declares <|tool_call> as an implicit end delimiter the same as Qwen's <tool_call> so a tool call ends the open thought. It is matched by token id when it is a single token.
@abra-code

Copy link
Copy Markdown
Contributor Author

@davidkoski Thanks for the repros, they were very helpful. I believe I addressed all the review comments now. Please review again.

@davidkoski davidkoski left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think this is in a good spot, thank you for the contribution!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants